﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using Model;

namespace TaxiDispatchClient
{
    public partial class TaxiOfCdmaForm : DevExpress.XtraEditors.XtraForm
    {
        public TaxiOfCdmaForm()
        {
            InitializeComponent();
        }

        private Thread _thread;
        private bool _isLoad;
        private bool _isAdd;


        private void SpecialCarForm_Load(object sender, EventArgs e)
        {
 
            //foreach (string s in MainForm.CompanyList)
            //{
            //    comboBoxEdit_company.Properties.Items.Add(s);
            //}

            _isLoad = true;
            _thread = new Thread(BindGrid);
            _thread.Start();
        }

        private void BindControlData()
        {
            DataSet dsCompany = new DataSet();

            if (MainForm.MyUserInfo.CompanyName == Service.PowerConfig.MainCompanyName)
            {
                dsCompany = MainForm.PositionService.CompanyGetList(""); 
            }
            else
            {
                dsCompany = MainForm.PositionService.CompanyGetList(
                    "CompanyName like '"+MainForm.MyUserInfo.CompanyName
                    +"%'");
            }
            if (dsCompany != null && dsCompany.Tables.Count > 0)
            {
                foreach (DataRow row in dsCompany.Tables[0].Rows)
                {
                    string id = row["Id"].ToString();
                    string name = row["CompanyName"].ToString();
                    ImageComboBoxItem item = new ImageComboBoxItem();
                    item.Description = name;
                    item.Value = id;
                    BeginInvoke(new MethodInvoker(() =>
                    {
                        comboBoxEdit_company.Properties.Items.Add(item);
                        imageCombo_companySel.Properties.Items.Add(item);
                    }));
                }
            }
              
        }
        private void BindGrid()
        {
            try
            {
                DataSet ds = new DataSet();
                StringBuilder strWhere = new StringBuilder();
                string parameterVaule = textEdit_condition.Text.Trim();
              
                if (parameterVaule.Trim()!="")
                {
                    if (radioGroup_SelectType.SelectedIndex == 1)
                    {
                        strWhere.Append("(DriverDay like '%");
                        strWhere.Append(parameterVaule);
                        strWhere.Append("%' or DriverDay like '%");
                        strWhere.Append(parameterVaule);
                        strWhere.Append("%') ");
                    }
                    else if (radioGroup_SelectType.SelectedIndex == 2)
                    { 
                        strWhere.Append("(PhoneNumberDay like '%");
                        strWhere.Append(parameterVaule);
                        strWhere.Append("%' or PhoneNumberNight like '%");
                        strWhere.Append(parameterVaule);
                        strWhere.Append("%') ");
                    }
                    else if (radioGroup_SelectType.SelectedIndex == 4 &&
                        imageCombo_companySel.SelectedIndex>=0)
                    {
                        strWhere.Append(" CompanyId=");
                        parameterVaule = imageCombo_companySel.Properties.Items[
                            imageCombo_companySel.SelectedIndex].Value.ToString();
                        strWhere.Append(parameterVaule);
                    }
                    else
                    {
                        //string parameter = imageCombo_typeSelect.Properties.Items[
                        //      imageCombo_typeSelect.SelectedIndex].Value.ToString();
                        string parameter = radioGroup_SelectType.Properties.Items[
                            radioGroup_SelectType.SelectedIndex].Value.ToString();
                        strWhere.Append(parameter);
                        strWhere.Append(" like '%");
                        strWhere.Append(parameterVaule);
                        strWhere.Append("%' ");
                    }
                }
                if (MainForm.MyUserInfo.CompanyName != Service.PowerConfig.MainCompanyName)
                {
                    if (strWhere.ToString()!="")
                    {
                        strWhere.Append(" and ");
                    }
                    strWhere.Append("  CompanyName='");
                    strWhere.Append(MainForm.MyUserInfo.CompanyName);
                    strWhere.Append("'");
                }
                   
                ds = MainForm.PositionService.CdmaTaxiGetList(strWhere.ToString());
                if (ds != null && ds.Tables.Count == 1)
                {
                    ClearInputControl();
                     
                    BeginInvoke(new MethodInvoker(() =>
                    {

                        gridControl1.DataSource = ds.Tables[0];
                        gridView1.GroupPanelText = "出租车列表-共" + ds.Tables[0].Rows.Count + "辆";
                        if (_isLoad)
                        {
                            BindControlData();
                            _isLoad = false;
                        }
                        if (_isAdd)
                        {
                            gridView1.FocusedRowHandle = gridView1.RowCount - 1;
                            _isAdd = false;
                        }                      
                        btn_select.Enabled = true;
                    }));
                }
                   
            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex);
                //  BeginInvoke(new MethodInvoker(() => btn_select.Enabled = true));               
            }
        }
 

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);//
            if (row != null)
            {
                label_id.Text = row["Id"].ToString(); 
                textEdit_DeviceNumber.Text = row["DeviceNumber"].ToString();
                textEdit_carNo.Text = row["TaxiNo"].ToString(); 
                textEdit_carType.Text = row["TaxiType"].ToString();
                textEdit_driverNameDay.Text = row["DriverDay"].ToString();
                textEdit_driverNameNight.Text = row["DriverNight"].ToString();
                textEdit_phoneNumDay.Text = row["PhoneNumberDay"].ToString();
                textEdit_phoneNumNight.Text = row["PhoneNumberNight"].ToString();
                comboBoxEdit_company.Text = row["CompanyId"].ToString();
                memoEdit_remark.Text = row["Remark"].ToString();
                textEdit_SIM.Text = row["SIM"].ToString();

                btn_modify.Enabled = true;
              
                if (MainForm.MyUserInfo.CompanyName != Service.PowerConfig.MainCompanyName)
                {
                    comboBoxEdit_company.SelectedIndex = 0;
                }
            }
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);//
            if (row != null)
            {
                label_id.Text = row["Id"].ToString();
                textEdit_SIM.Text = row["SIM"].ToString();
                textEdit_DeviceNumber.Text = row["DeviceNumber"].ToString();
                textEdit_carNo.Text = row["TaxiNo"].ToString();
                textEdit_carType.Text = row["TaxiType"].ToString();
                textEdit_driverNameDay.Text = row["DriverDay"].ToString();
                textEdit_driverNameNight.Text = row["DriverNight"].ToString();
                textEdit_phoneNumDay.Text = row["PhoneNumberDay"].ToString();
                textEdit_phoneNumNight.Text = row["PhoneNumberNight"].ToString();
                comboBoxEdit_company.Text = row["CompanyId"].ToString();
                memoEdit_remark.Text = row["Remark"].ToString();
                btn_modify.Enabled = true;
                 
                if (MainForm.MyUserInfo.CompanyName != Service.PowerConfig.MainCompanyName)
                {
                    comboBoxEdit_company.SelectedIndex = 0;
                }
            }
        }


        private void simpleButton_add_Click(object sender, EventArgs e)
        {
            if (btn_add.Tag.ToString() == "新增")
            {
                label_id.Text = "";
                textEdit_DeviceNumber.Text = "";
                textEdit_carNo.Text = "";
                textEdit_carType.Text = "";
                textEdit_driverNameDay.Text = "";
                textEdit_driverNameNight.Text = "";
                textEdit_phoneNumDay.Text = "";
                textEdit_phoneNumNight.Text = "";
                memoEdit_remark.Text = "";
                comboBoxEdit_company.Text = "";

                SetInPutEnable(true);

               
                gridControl1.Enabled = false;
                btn_select.Enabled = false;
                btn_modify.Visible = false;
                btn_delete.Visible = false;
                btn_cancel.Visible = true;
                btn_cancel.Location = btn_modify.Location;
                btn_add.Tag = "保存";
                btn_add.Image = Properties.Resources.UserForm_btnsave001;
            }
            else
            {
                if (!CheckInput()) return;
                string sim = textEdit_SIM.Text;           
                string deviceNumber = textEdit_DeviceNumber.Text;
                string taxiNo = textEdit_carNo.Text;
                string taxiType = textEdit_carType.Text ;
                string driverDay = textEdit_driverNameDay.Text;
                string driverNight = textEdit_driverNameNight.Text;
                string phoneNumDay = textEdit_phoneNumDay.Text;
                string phoneNumNight = textEdit_phoneNumNight.Text;
                string remark = memoEdit_remark.Text;
                int companyId = int.Parse(comboBoxEdit_company.Properties.Items[
                    comboBoxEdit_company.SelectedIndex].Value.ToString());

                if (PhoneNumberExist(phoneNumDay)) return;
                if (PhoneNumberExist(phoneNumNight)) return;  

                try
                {
                    TaxiCdmaInfo model = new TaxiCdmaInfo
                    {       
                        SIM = sim,
                        DeviceNumber = deviceNumber,
                        TaxiNo =taxiNo,
                        TaxiType = taxiType,
                        DriverDay = driverDay,
                        DriverNight = driverNight,
                        PhoneNumberDay = phoneNumDay,
                        PhoneNumberNight = phoneNumNight,                        
                        CompanyId = companyId,
                        Remark  = remark
                    };
                    if (MainForm.PositionService.CdmaTaxiAdd(model))
                    {
                        XtraMessageBox.Show("添加成功");
                        gridControl1.Enabled = true;
                        btn_select.Enabled = true;
                        btn_delete.Visible = true;
                        btn_modify.Visible = true;
                        btn_cancel.Visible = false;

                        SetInPutEnable(false);
                         
                        btn_add.Tag = "新增";
                        btn_add.Image = Properties.Resources.UserForm_btnadd001;
                        _isAdd = true;
                        _thread = new Thread(BindGrid);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("添加失败");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                    return;
                }


                //taxi.TaxiType=
            }

        }

        private void simpleButton_modify_Click(object sender, EventArgs e)
        {
            if (label_id.Text == string.Empty)
            {
                XtraMessageBox.Show("请选择要修改的出租车！");
                return;
            }
            if (btn_modify.Tag.ToString() == "修改")
            {
                SetInPutEnable(true); 
                gridControl1.Enabled = false;
                btn_select.Enabled = false;
                btn_delete.Visible = false;
                btn_cancel.Visible = true;
                btn_cancel.Location = btn_modify.Location;
                btn_modify.Location = btn_add.Location;
                btn_add.Visible = false;
                btn_modify.Tag = "保存";
                btn_modify.Image = Properties.Resources.UserForm_btnsave001;
            }
            else
            {
                if (!CheckInput()) return;
                      
                int id = int.Parse(label_id.Text);
                string sim = textEdit_SIM.Text;
                string deviceNumber = textEdit_DeviceNumber.Text; 
                string taxiNo = textEdit_carNo.Text;
                string taxiType = textEdit_carType.Text;
                string driverDay = textEdit_driverNameDay.Text;
                string driverNight = textEdit_driverNameNight.Text;
                string phoneNumDay = textEdit_phoneNumDay.Text;
                string phoneNumNight = textEdit_phoneNumNight.Text;
                string remark = memoEdit_remark.Text;
                int companyId = int.Parse(comboBoxEdit_company.Properties.Items[
                    comboBoxEdit_company.SelectedIndex].Value.ToString());

                if (PhoneNumberExist(phoneNumDay, id)) return;
                if (PhoneNumberExist(phoneNumNight, id)) return;  

                TaxiCdmaInfo model = new TaxiCdmaInfo
                {
                    Id = id,
                    SIM = sim,
                    DeviceNumber = deviceNumber,
                    TaxiNo = taxiNo,
                    TaxiType = taxiType,
                    DriverDay = driverDay,
                    DriverNight = driverNight,
                    PhoneNumberDay = phoneNumDay,
                    PhoneNumberNight = phoneNumNight,
                    CompanyId = companyId,
                    Remark = remark
                };
                try
                {
                    if (MainForm.PositionService.CdmaTaxiUpdate(model))
                    {
                        XtraMessageBox.Show("修改成功！");

                        gridControl1.Enabled = true;
                        btn_select.Enabled = true;
                        btn_delete.Visible = true;
                        btn_add.Visible = true;
                        btn_modify.Location = btn_cancel.Location;
                        btn_cancel.Visible = false;
                        btn_modify.Tag = "修改";
                        btn_modify.Image = Properties.Resources.UserForm_btnmodify001;
                         
                        SetInPutEnable(false);
                       

                        //btn_add.Enabled = false;

                        _thread = new Thread(BindGrid);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("修改失败！");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                    return;
                }
            }
        }

        private void simpleButton_delete_Click(object sender, EventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);
            string id;
            if (row == null)
            {
                XtraMessageBox.Show("请选择要删除的车辆！");
                return;
            }
            id = row["id"].ToString();
            string phoneNum = row["TaxiNo"].ToString();
            if (XtraMessageBox.Show("确认删除牌照为【" + phoneNum 
                + "】的数据吗？", "警告", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    if (MainForm.PositionService.CdmaTaxiDelete(int.Parse(id)))
                    {
                        XtraMessageBox.Show("删除成功！");
                        _thread = new Thread(BindGrid);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("删除失败！");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                }

            }
        }

        private void simpleButton_Select_Click(object sender, EventArgs e)
        {
            gridView1.GroupPanelText = "数据加载中...";
            btn_select.Enabled = false;
            _thread = new Thread(BindGrid);
            _thread.Start();
        }

        private void simpleButton_cancle_Click(object sender, EventArgs e)
        {
            gridView1_RowClick(null, null);
            gridControl1.Enabled = true;
            btn_select.Enabled = true;
            btn_delete.Visible = true;
            btn_cancel.Visible = false;
            btn_add.Visible = true;
            btn_add.Tag = "新增";
            btn_add.Image = Properties.Resources.UserForm_btnadd001;
            btn_modify.Visible = true;
            btn_modify.Tag = "修改";
            btn_modify.Image = Properties.Resources.UserForm_btnmodify001;
            btn_modify.Location = btn_cancel.Location;

            SetInPutEnable(false);

        }

        public void ClearInputControl()
        {
            BeginInvoke(new MethodInvoker(() =>
                {
                    label_id.Text = "";
                    textEdit_DeviceNumber.Text = "";
                    textEdit_carNo.Text = "";
                    textEdit_carType.Text = "";
                    textEdit_driverNameDay.Text = "";
                    textEdit_driverNameNight.Text = "";
                    textEdit_phoneNumDay.Text = "";
                    textEdit_phoneNumNight.Text = "";
                    comboBoxEdit_company.Text = "";
                    memoEdit_remark.Text = "";
                    textEdit_SIM.Text = "";
                }));            
        }
         
        public void SetInPutEnable(bool enable)
        {
             BeginInvoke(new MethodInvoker(() =>
                {
                    textEdit_DeviceNumber.Enabled = enable;
                    textEdit_carNo.Enabled = enable;
                    textEdit_carType.Enabled = enable;
                    textEdit_driverNameDay.Enabled = enable;
                    textEdit_driverNameNight.Enabled = enable;
                    textEdit_phoneNumDay.Enabled = enable;
                    textEdit_phoneNumNight.Enabled = enable;
                    comboBoxEdit_company.Enabled = enable;
                    memoEdit_remark.Enabled = enable;
                    textEdit_SIM.Enabled = enable;
                }));         
        }

        private bool PhoneNumberExist(string phoneNumber, int id = 0)
        {
            if (MainForm.PositionService.DriverExistphone(phoneNumber))
            {
                XtraMessageBox.Show("手机号"+phoneNumber+"已被使用,请核对！（已存在于司机表中）");
                return true;
            }
            string strWhere = " (PhoneNumberDay ='" + phoneNumber + "' or PhoneNumberNight='"
                +phoneNumber+"') ";            
             
            if (id!=0)
            {                 
                strWhere += " and t.Id != " + id;
            }
            DataSet ds = MainForm.PositionService.CdmaTaxiGetList(strWhere);
            if (ds != null && ds.Tables.Count == 1 && ds.Tables[0].Rows.Count > 0)
            {
                XtraMessageBox.Show("手机号" + phoneNumber + "已被使用,请核对！（已存在于CDMA类出租车表中）");
                return true;
            }
            return false;
        }

        private bool CheckInput()
        {
            string sim = textEdit_SIM.Text;
            string deviceNumber = textEdit_DeviceNumber.Text;
            string taxiNo = textEdit_carNo.Text;
            string taxiType = textEdit_carType.Text;
            string driverDay = textEdit_driverNameDay.Text;
            string driverNight = textEdit_driverNameNight.Text;
            string phoneNumDay = textEdit_phoneNumDay.Text;
            string phoneNumNight = textEdit_phoneNumNight.Text;

            if (sim.Length > 15)
            {
                XtraMessageBox.Show("SIM号码长度太长！");
                textEdit_SIM.Focus();
                return false;
            }
            if (deviceNumber == string.Empty)
            {
                XtraMessageBox.Show("设备编号（IMEI）不能为空");
                textEdit_DeviceNumber.Focus();
                return false;
            }

            if (Encoding.GetEncoding("GBK").GetBytes(deviceNumber).Length > 25)
            {
                XtraMessageBox.Show("设备编号（IMEI）长度太长,最多为25个字符！");
                textEdit_DeviceNumber.Focus();
                return false;
            }

            if (Encoding.GetEncoding("GBK").GetBytes(taxiNo).Length > 8)
            {
                XtraMessageBox.Show("车辆牌照号码输入长度太长,最多8字节！");
                textEdit_carNo.Focus();
                return false;
            }
            if (Encoding.GetEncoding("GBK").GetBytes(taxiType).Length > 20)
            {
                XtraMessageBox.Show("出租车车型输入长度太长,最多10个字节");
                textEdit_carType.Focus();
                return false;
            }
              
            if (driverDay == string.Empty)
            {
                XtraMessageBox.Show("白班司机姓名不能为空！");
                textEdit_driverNameDay.Focus();
                return false;
            }

            if (Encoding.GetEncoding("GBK").GetBytes(driverDay).Length > 25)
            {
                XtraMessageBox.Show("白班司机姓名长度太长,最多为10个字节！");
                textEdit_driverNameDay.Focus();
                return false;
            }
            if (phoneNumDay == string.Empty)
            {
                XtraMessageBox.Show("白班司机手机号码不能为空！");
                textEdit_phoneNumDay.Focus();
                return false;
            }           
            if (driverNight == string.Empty)
            {
                XtraMessageBox.Show("夜班司机姓名不能为空！");
                textEdit_driverNameNight.Focus();
                return false;
            } 
            if (Encoding.GetEncoding("GBK").GetBytes(driverNight).Length > 25)
            {
                XtraMessageBox.Show("夜班司机姓名长度太长,最多为10个字节！");
                textEdit_driverNameNight.Focus();
                return false;
            }
            if (phoneNumNight == string.Empty)
            {
                XtraMessageBox.Show("夜班司机手机号码不能为空！");
                textEdit_phoneNumNight.Focus();
                return false;
            }

            if (comboBoxEdit_company.SelectedIndex < 0
               || comboBoxEdit_company.Text == "")
            {
                XtraMessageBox.Show("请选择出租车所属公司");
                comboBoxEdit_company.Focus();
                return false;
            }

            return true;
        }

        #region  窗体控件操作、效果
        Point _mouseOff;
        bool _leftFlag;
        private void Taxi_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Taxi_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Taxi_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }
        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Default;
        }
        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }

        #endregion

        private void btn_exportToExcel_Click(object sender, EventArgs e)
        {
            saveFileDialog1.FileName = "车辆列表";
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                gridView1.ExportToXls(saveFileDialog1.FileName);
                XtraMessageBox.Show("Excel导出完成！");
            }
        }

        private void From_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_thread != null)
            {
                _thread.Abort();
            }
        }
         
        private void textEdit_condition_KeyPress(object sender, KeyPressEventArgs e)
        {

            if ((Keys)e.KeyChar == Keys.Enter)
            {
                simpleButton_Select_Click(null, null);
            }

        }

        private void radioGroup_SelectType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (radioGroup_SelectType.SelectedIndex == 4)
            {
                imageCombo_companySel.Location = textEdit_condition.Location;
                imageCombo_companySel.Visible = true;
               
                textEdit_condition.Visible = false;
            }
            else
            {
                textEdit_condition.Visible = true;
                imageCombo_companySel.Visible = false;
                           
            }
        }

      
    }
}